
var fm = Ext.form;
var base_url = '<?php echo base64_decode($_GET['baseUrl']);?>';

var total_row = 20;
var order_status = '<?php echo $_GET['order_status'] ?>';
var proxy = new Ext.data.ScriptTagProxy({
 	api: {
        read : base_url+'admin/air_freightorder/grid.html?order_status='+order_status,
        create : base_url+'admin/air_freightorder/add.html',
        update: base_url+'admin/air_freightorder/add.html',
        destroy: base_url+'admin/air_freightorder/delete.html'
    }
});

var writer = new Ext.data.JsonWriter({
    encode: true
});

var store = new Ext.data.JsonStore({
	start : 'start',
	remoteSort: true,
    totalProperty: 'total',
    proxy: proxy,
    root: 'data',
    fields : [
              {name: 'id'},
{name: 'order_day',type:'date'},
{name: 'shipper_company'},
{name: 'consignee'},
{name: 'hawb'},
{name: 'comment_for_agent'},
{name: 'description'},
{name: 'edit',type: 'string'},
{name: 'view',type: 'string'}
          ],
	  listeners: {
	      save: function(s, b, d) {
	    	  store.save();
	      }
	  },
    writer: writer
});

var filters = new Ext.ux.grid.GridFilters({
    // encode and local configuration options defined previously for easier reuse
    encode: true, // json encode the filter query
    local: true,   // defaults to false (remote filtering)
    filters: [
{type: 'string',dataIndex: 'shipper_company'},
{type: 'string',dataIndex: 'consignee'},
{type: 'string',dataIndex: 'hawb'},
{type: 'string',dataIndex: 'description'},
{type: 'string',dataIndex: 'comment_for_agent'},
{type: 'date',  dataIndex: 'order_day'}
    ]
});
var createColModel = function () {

    var columns = [
    {header: 'ID',sort: 'id',dataIndex: 'id'},
{header: 'Order day',renderer: formatDate,sortable: true,sort: 'order_day',dataIndex: 'order_day',editor: new fm.DateField({format: 'd-m-Y'})},
{header: 'Shipper Company',sortable: true,sort: 'shipper_company',dataIndex: 'shipper_company',editor: new Ext.form.TextField()},
{header: 'Consignee',sortable: true,sort: 'consignee',dataIndex: 'consignee',editor: new Ext.form.TextField()},
{header: 'Description',sortable: true,sort: 'description',dataIndex: 'description',editor: new Ext.form.TextArea()},
{header: 'HAWB',sortable: true,sort: 'hawb',dataIndex: 'hawb',editor: new Ext.form.TextField()},
{header: 'Comment for agent',sort: 'comment_for_agent',dataIndex: 'comment_for_agent',editor: new Ext.form.TextArea()},
{header: 'Edit',dataIndex: 'edit',sortable: false},
{header: 'View',dataIndex: 'view',sortable: false}
               ];
if (order_status == 'processing'){
        columns.push({
            header: 'Status',
            xtype: 'actioncolumn',
            width: 50,
            items: [
                {
                    icon   : '/extjs/finish.gif',
                    altText : 'Finish',
                    tooltip: 'Finish this contact',
                    handler: function(grid, rowIndex, colIndex) {
                        var rec = store.getAt(rowIndex);
                        Ext.MessageBox.show({title:'Status Change',buttons: Ext.MessageBox.YESNO,animEl: 'samplebutton',icon: Ext.MessageBox.QUESTION,
                            msg: ' Do you really want to set status of this order to "Finish"?',
                            fn:function(buttonId){
                                if (buttonId == 'yes'){
                                    Ext.Ajax.request({
                                       url: base_url+'admin/air_freightorder/update_status.html',
                                       success: function(response, opts) {
                                            store.reload({params:{start:0, limit:total_row}});
                                       },
                                       params: { id: rec.get('id'),order_status:'finish' },
                                       method:'GET'
                                    });
                                }
                            }
                        });
                    }
                }
            ]
         });
    }
    return new Ext.grid.ColumnModel({
        columns: columns,
        defaults: {
            sortable: true
        }
    });
};
pagingBar = new Ext.PagingToolbar({
            store: store,
            pageSize: total_row,
            displayInfo: true,
            displayMsg: 'Displaying item {0} - {1} of {2}',
            emptyMsg: "No item to display",
            plugins: new Ext.ux.ProgressBarPager()
        });
Ext.onReady(function() {
    Ext.QuickTips.init();
    if (order_status == 'new'){
        var plugins = [new Ext.ux.grid.RowEditor({
           saveText: 'Update'
        }),filters];
    }else{
        var plugins = [filters];
    }
    var newsGrid = new Ext.grid.GridPanel({
        renderTo: 'news-grid',
        iconCls: 'icon-grid',
        frame: true,        
        height: 300,
        store: store,
        plugins: plugins,
        colModel: createColModel(),
        listeners: {
            render: {
                fn: function(){
                    store.load({
                        params: {
                            start: 0,
                            limit: total_row
                        }
                    });
                }
            }
        },
        tbar: [new Ext.form.ComboBox({
                     triggerAction: 'all',
                     lazyRender:false,
                     width:40,
                     mode: 'local',
                     store: new Ext.data.ArrayStore({
                         fields: [
                                  'id',
                                  'value'
                                 ],
                        data: [[10,'10'],[20,'20'],[50,'50'],[100,'100']]
                     }),
                     valueField: 'id',
                     displayField: 'value',
                     listeners:{
                          'select': function(combo,record ,index){
                        	  total_row = combo.getValue();
                        	  store.reload({params:{start:0, limit:total_row}});
                                  pagingBar.pageSize = total_row;
                        	  pagingBar.render();
                          }
                     }
                })
        ,'-',{
            text: 'Add',
            iconCls: 'silk-add',
            handler: onAdd
        }, '-', {
            text: 'Delete',
            iconCls: 'silk-delete',
            handler: onDelete
        }, '-'],
        bbar: pagingBar,
        viewConfig: {
            forceFit: true
        }
    });

    function onAdd(btn, ev) {
       window.location.href = base_url+'admin/air_freightorder/edit';
    }

    function onDelete() {
        Ext.MessageBox.show({
            title:'Delete item',
            msg: 'Do you really want to delete this item ?',
            buttons: Ext.MessageBox.YESNO,
            animEl: 'samplebutton',
            icon: Ext.MessageBox.QUESTION,
            fn:function(buttonId){
                if (buttonId == 'yes'){
                    var recs = newsGrid.getSelectionModel().getSelections() ;
                    if (!recs) {
                        return false;
                    }
                    for(var i in recs)
                    {
                        newsGrid.store.remove(recs[i]);
                    }
                }
            }
        });
    }
});
function formatDate(value){
    return value ? value.dateFormat('d-m-Y') : '';
}

function thickBoxPopup(id){
    Ext.Ajax.request({
       url: base_url+'admin/air_freightorder/details_view.html',
       success: function(response, opts) {
           var win = new Ext.Window({
                title: 'Order Detail',
                resizable:false,
                preventBodyReset:true,
                bodyStyle:'background-color: #FFF',
                width:600,
                height:500,
                autoScroll:true,
                html: response.responseText,
                listeners:{
                      'close': function(){
                            if (order_status == 'new'){
                                store.reload({params:{start: 0,limit: total_row}});
                            }
                      }
                }
            });
            win.show();
        },
       params: { id: id },
       method:'GET'
    });
}